/*************************************************************************
    > File Name: exercise1-2.cpp
    > Author: Botao
    > Mail: peng.botao@aliyun.com 
    > Created Time: Thu 11 Nov 2021 01:38:09 PM CST
 ************************************************************************/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <string>
void *str[5];

int main()
{
    int i = 8;
    while (true)
    {
        i++;
        str[0] = malloc(1024 * i);
        str[1] = malloc(1024 * i);
        str[2] = malloc(1024 * i);
        str[3] = malloc(1024 * i);
        str[4] = malloc(1024 * i);
        printf("Before malloc()s.\n");

        FILE *fp = fopen("./text.txt", "r");
        if (!fp)
        {
            printf("Open failed!");
            return 0;
        }

        fread(str[0], 1, sizeof(str[0]), fp);
        fread(str[1], 1, sizeof(str[1]), fp);
        fread(str[2], 1, sizeof(str[2]), fp);
        fread(str[3], 1, sizeof(str[3]), fp);
        fread(str[4], 1, sizeof(str[4]), fp);
        printf("The value where str[1] stored can be read now: %s\n", str[1]);
        printf("The value where str[3] stored can be read now: %s\n", str[3]);

        printf("After 5 malloc()s.\n");

        free(str[1]);
        free(str[3]);

        printf("After 2 free()s.\n");
        if (str[1])
        {
            printf("when the size of space allocated is %dKB\n", 5 * 1024 * i);
            printf("The value where str[1] stored can be read now: %s\n", str[1]);
        }

        if (str[3])
        {
            printf("when the size of space allocated is %dKB\n", 5 * 1024 * i);
            printf("The value where str[3] stored can be read now: %s\n\n", str[3]);
        }

        fclose(fp);
        free(str[1]);
        free(str[3]);
    }
    return 0;
}
